<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 闹闹派单
 -->

<template>
  <div>
    <van-form class="noisy">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.user"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field v-model="ruleForm.pass" type="password" label="密码" placeholder="请填写密码" clearable />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountList" :key="index" center :title="list.wangwang">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import * as noisy from "@/api/noisy";
export default {
  name: "Noisy",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        user: "13567368963",
        pass: "19990210"
      },
      // 循环时间
      IntervalTime: 8,
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      accountList: [],
      show: false,
      // uid
      uid: "",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: "",
      task_num: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 19 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 19 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.user = this.item.user;
        this.ruleForm.pass = this.item.pass;
        this.type = this.item.type || "0";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 19 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.user = this.item.user;
      this.ruleForm.pass = this.item.pass;
      this.type = this.item.type || "0";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.headers = "";
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        let param = {
          type: "post",
          data: this.ruleForm
        };
        noisy.ajaxFun(noisy.getLogin, param, res => {
          if (res) {
            _this.returnContent.unshift(alertMsg(res.msg));
            if (res.errno === 0) {
              // 登录成功  => 保存账号信息
              saveInfo({
                user: _this.ruleForm.user,
                pass: _this.ruleForm.pass,
                type: _this.type,
                index: _this.index
              });
              _this.uid = res.data.uid;
              _this.onGetAccountList(_this);
            } else {
              _this.startFlag = false;
            }
          } else {
            let param = {
              type: "post",
              data: this.ruleForm
            };
            noisy.ajaxFun(noisy.getLogin, param, res => {
              if (res) {
                _this.returnContent.unshift(alertMsg(res.msg));
                if (res.errno === 0) {
                  // 登录成功  => 保存账号信息
                  saveInfo({
                    user: _this.ruleForm.user,
                    pass: _this.ruleForm.pass,
                    type: _this.type,
                    index: _this.index
                  });
                  _this.uid = res.data.uid;
                  _this.onGetAccountList(_this);
                } else {
                  _this.startFlag = false;
                }
              }
            });
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取买号
    onGetAccountList(_this) {
      let param = {
        type: "post",
        headers: "",
        data: {
          uid: _this.uid
        }
      };
      noisy.ajaxFun(noisy.getAccountList, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.errno === 0) {
          _this.accountList = res.data;
          if (_this.accountList.length === 1) {
            _this.onChange(_this.accountList[0]);
          } else {
            _this.show = true;
          }
        } else {
          _this.startFlag = false;
        }
      });
    },
    // 选择账号
    onChange(list) {
      const _this = this;
      clearInterval(_this.timer);
      _this.show = false;
      _this.returnContent.unshift(
        alertMsg("接单号: " + list.wangwang + " 即将开始接单，请耐心等待...")
      );
      _this.onGetTaskList(_this, list.wangwang);
    },
    // 任务列表
    onGetTaskList(_this, wang) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        headers: "",
        data: {
          addr: "鹿城区滨海路",
          addrs: "浙江省",
          uid: _this.uid,
          version: "1.0.5",
          wang: wang
        }
      };
      noisy.ajaxFun(noisy.getTaskList, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.errno == 0) {
          // 接单
          _this.task_num = res.data.task_num;
          _this.onGetAcceptTask("鹿城区滨海路", wang, _this);
        } else {
          // 暂无数据 => 循环请求
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetTaskList(_this, wang);
            }
          }, _this.IntervalTime * 1000);
        }
      });
    },
    // 接单
    onGetAcceptTask(addr, wang, _this) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        headers: "",
        data: {
          addr: addr,
          uid: _this.uid,
          task_num: _this.task_num,
          wang: wang
        }
      };
      noisy.ajaxFun(noisy.getAcceptTask, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.errno == 0) {
          _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ["接单成功，请前往做单..."]
          });
        } else {
          _this.timer = setInterval(() => {
            _this.onGetTaskList(_this, wang)
          }, _this.IntervalTime * 1000)
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>